package com.jumper.study.admin.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumper.study.admin.dto.req.OrderPriceReq;
import com.jumper.study.admin.dto.req.OrderSearchReq;
import com.jumper.study.admin.dto.resp.OrderOperateResp;
import com.jumper.study.admin.dto.resp.OrderResp;
import com.jumper.study.admin.dto.resp.OrderStatusResp;
import com.jumper.study.admin.service.OrderService;
import com.jumper.study.common.api.CommonPageResult;
import com.jumper.study.common.api.CommonResult;
import com.jumper.study.common.util.AdminUtil;
import com.jumper.study.db.dto.OrderDto;
import com.jumper.study.db.model.Order;
import com.jumper.study.db.model.OrderOperate;
import com.jumper.study.db.model.OrderStatus;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;




@RestController
@RequestMapping("/api/backend/orders")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private AdminUtil adminUtil;

    @PostMapping("")
    public CommonPageResult<List<OrderResp>> pageList(@RequestBody OrderSearchReq req) {
        Page<OrderDto> page = Page.of(req.getPage(), req.getLimit());
        List<OrderDto> dtos = orderService.pageSearchWithAccountAndLesson(page, req).getRecords();
        List<OrderResp> resp = dtos.stream().map(
            dto -> new OrderResp(dto.getId(), dto.getOrderNo(), dto.getAccountId(), dto.getStudentName(), dto.getLessonId(), dto.getLessonTitle(),
                dto.getStatus(), dto.getPrice(), dto.getCreatedAt())
        ).toList();

        return CommonPageResult.restPage(page.getCurrent(), page.getSize(), page.getTotal(), resp);
    }
    
    @GetMapping("/{id}")
    public CommonResult<Object> getItem(@PathVariable Long id) {
        OrderDto dto = orderService.getWithAccountAndLessonById(id);
        if (dto == null) {
            return CommonResult.notFound();
        }
        OrderResp resp = new OrderResp(dto.getId(), dto.getOrderNo(), dto.getAccountId(), dto.getStudentName(), dto.getLessonId(), dto.getLessonTitle(),
            dto.getStatus(), dto.getPrice(), dto.getCreatedAt());

        return CommonResult.success(resp);
    }
    
    //修改价格
    @PostMapping("/{id}/price")
    public CommonResult<Boolean> updatePrice(@PathVariable Long id, @RequestBody OrderPriceReq req) {
        Order order = orderService.getById(id);
        if (order == null) {
            return CommonResult.notFound();
        }
        if (!order.canUpdatePrice()) {
            return CommonResult.failed("订单价格不可调，请确认订单状态");
        }
        boolean result = orderService.updatePrice(order, req.getPrice(), adminUtil.getAdminId());

        return CommonResult.success(result);
    }
    
    //完成订单，并开通课程
    @PostMapping("/{id}/complete")
    public CommonResult<Boolean> updateComplete(@PathVariable Long id) {
        Order order = orderService.getById(id);
        if (order == null) {
            return CommonResult.notFound();
        }
        boolean result = orderService.complete(order, adminUtil.getAdminId());
        return CommonResult.success(result);
    }
    
    //取消订单，并关闭学员开通的课程
    @PostMapping("/{id}/cancel")
    public CommonResult<Boolean> cancel(@PathVariable Long id) {
        Order order = orderService.getById(id);
        if (order == null) {
            return CommonResult.notFound();
        }
        boolean result = orderService.cancel(order, id);
        return CommonResult.success(result);
    }
    
    //订单操作日志
    @GetMapping("/{id}/operates")
    public CommonResult<Object> getOperates(@PathVariable Long id) {
        List<OrderOperate> operates = orderService.listOperaters(id);
        List<OrderOperateResp> resp = operates.stream().map(
            entity -> new OrderOperateResp(entity.getId(), entity.getAdminId(), entity.getAdminName(), entity.getOperate(), entity.getDescription(), entity.getCreatedAt())
        ).toList();

        return CommonResult.success(resp);
    }
    
    //订单状态变化 
    @GetMapping("/{id}/statuses")
    public CommonResult<Object> getStatuses(@PathVariable Long id) {
        List<OrderStatus> statuses = orderService.listStatuses(id);
        List<OrderStatusResp> resp = statuses.stream().map(
            entity -> new OrderStatusResp(entity.getId(), entity.getAdminId(), entity.getAdminName(), 
                entity.getPreStatus(), entity.getStatus(), entity.getOperateId(), entity.getCreatedAt())
        ).toList();

        return CommonResult.success(resp);
    }
    
}
